<template>
    <ul class="pager-container" v-if="total_page > 1">
        <li v-show="cur_page > 4" @click="page_change(1)">首页</li>
        <li v-show="cur_page !== 1" @click="page_change(cur_page - 1)">&lt;</li>
        <li
            v-for="p in page_list"
            :key="p"
            :class="{ active: cur_page === p }"
            @click="page_change(p)"
        >
            {{ p }}
        </li>
        <li v-show="cur_page !== total_page" @click="page_change(cur_page + 1)">
            &gt;
        </li>
        <li
            v-show="cur_page <= total_page - 4"
            @click="page_change(total_page)"
        >
            尾页
        </li>
    </ul>
</template>

<script>
export default {
    props: {
        cur_page: {
            type: Number,
            default: 1,
        },
        total_page: {
            type: Number,
            default: 0,
        },
        page_range: {
            // 页码范围
            type: Number,
            default: 3,
        },
    },
    computed: {
        page_list() {
            const start =
                this.cur_page - this.page_range < 1
                    ? 1
                    : this.cur_page - this.page_range;
            const end =
                this.cur_page + this.page_range > this.total_page
                    ? this.total_page
                    : this.cur_page + this.page_range;
            return new Array(end - start + 1)
                .fill(start)
                .map((item, i) => item + i);
        },
    },
    methods: {
        page_change(page) {
            if (page === this.cur_page) {
                // 点击当前页不处理
                return;
            }
            // 抛出事件给父组件，传入事件名及参数
            this.$emit("page_change", page);
            // vue 实例中的方法
        },
    },
};
</script>

<style lang="less">
@import "~@/styles/var.less";
.pager-container {
    width: max-content;
    display: flex;
    justify-content: space-between;
    li {
        padding: 0 5px;
        margin: 0 7px;
        min-width: 30px;
        box-sizing: border-box;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 5px;
        border: 1px solid;
        cursor: pointer;
        color: @words;
        &:hover {
            color: @primary;
        }
        &.active {
            color: #fff;
            background-color: @primary;
            border-color: @primary;
        }
    }
}
</style>
